import React, { useEffect, useState } from 'react';
import styles from './style/index.module.less';
import { Table, TableColumnProps, Card, Space, Button,Drawer,Form,Input,InputNumber, Notification  } from '@arco-design/web-react';
import { v4 as uuidv4 } from 'uuid';
import { confirmDelete } from '@/utils/util';

const DS = 'Datasource'
const formItemLayout = {
  wrapperCol: {
    span: 24,
  },
};
function getColumns(
  callback: (record: Record<string, any>, type: string) => Promise<void>
) {
  return [
    {
      title: '连接名称',
      dataIndex: 'name',
    }, 
    {
      title: '主机名',
      dataIndex: 'host',
    },
    {
      title: '端口',
      dataIndex: 'port',
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 160,
      render: (v, record) => (
        <>
        
          <Button
            type="text"
            size="small"
            onClick={() => callback(record, 'edit')}
          >编辑           
          </Button>
          <Button
            type="text"
            size="small"
            onClick={() => callback(record, 'delete')}
          >
              删除
          </Button>
        
        </>
      ),
    },
  ];
}

const initData = [
  {
    id: '1',
    type: 'MySQL',
    name: '137 dev',
    port: 3306,
    host: '127.0.0.1',
    username: 'jane',
  },
  {
    id: '2',
    type: 'MySQL',
    name: '137 dev',
    port: 3306,
    host: '127.0.0.1',
    username: 'jane',
  },
  {
    id: '3',
    type: 'MySQL',
    name: '137 dev',
    port: 3306,
    host: '127.0.0.1',
    username: 'jane',
  },
];

const defaultData = {
  id: '',
  type: 'MySQL',
  name: '',
  port: 3306,
  host: '127.0.0.1',
  username: 'root',
  password: '',
}

function DataSource() {
  const [data,setData] = useState([])
  const [title,setTitle] = useState('')
  const [visible,setVisible] = useState(false)

  const [editForm] = Form.useForm();
  
  useEffect(() => {
    setData(readData())
  }, []);
  const tableCallback = async (record, type) => {
    console.log(record)
    if('edit'===type){
      onAddEdit(record.id)
    }else if('delete'==type){
      confirmDelete('确定要删除连接吗',()=>{
        doDelete(record.id)
      })
    }
  };
  const doDelete = (id)=>{
    let arr =[]
    data.forEach((v)=>{
      if( v.id != id){
        arr.push(v)
      }
    })
    setData(arr)
    Notification.info({position: 'bottomLeft',content:'删除成功！'})
  }
  const readData = ()=> {
    let ds = localStorage.getItem(DS)
    if(ds){
      return JSON.parse(ds)
    }
    return []
  }
  const saveData = (arr)=>{
    localStorage.setItem(DS,JSON.stringify(arr))
  }
  const onOk =()=>{
    let  item = editForm.getFieldsValue()
    let arr =[]
    let match = false
    data.forEach((v)=>{
      if( v.id == item.id){
        arr.push(item)
        match = true
      }else{
        arr.push(v)
      }
    })
    if(!match){
      arr.push(item)
    }
    setData(arr)
    saveData(arr)
    Notification.info({
      position: 'bottomLeft',
      content: '添加成功'
    })
    setVisible(false)
  }
  const onAddEdit = (id)=>{
    data.map((val)=>{
      if (id==val.id){
        editForm.setFieldsValue(val)
        setVisible(true)
        setTitle('编辑数据库连接')
      }
    })
  }
  const add =()=>{
    let addData = {...defaultData, id:uuidv4()}
    editForm.setFieldsValue(addData)
    setTitle('添加数据库连接')
    setVisible(true)
  }
  return (
    <div className={styles.container}>
      <Card style={{ width: '100%' }} title='数据库连接' extra={
        <Space>
          <Button size='small' type='primary' onClick={add}>添加</Button>
        </Space>
      }>
        <Table
          rowKey='id'
          columns={getColumns(tableCallback)}
          data={data}
          pagination={false}
          size='small'
        />
      </Card>
      <Drawer
        width={600}
        title={title}
        visible={visible}
        maskClosable={false}
        onOk={onOk}
        onCancel={() => {
          setVisible(false);
        }}
      >
      <Form {...formItemLayout} form={editForm} layout='vertical'>
        <Form.Item hidden={true} field='id'><Input /></Form.Item>
        <Form.Item label='连接名称' field='name' rules={[{ required: true }]}>
          <Input placeholder='请输入连接名称' />
        </Form.Item>
        <Form.Item label='主机名/IP' field='host' rules={[{ required: true }]}>
          <Input placeholder='请输入主机名/IP' />
        </Form.Item>
        <Form.Item label='端口' field='port'>
          <Input placeholder='请输入端口' />
        </Form.Item>
        <Form.Item label='用户名' field='username'>
          <Input placeholder='请输入用户名' />
        </Form.Item>
        <Form.Item label='密码' field='password'>
          <Input placeholder='请输入密码' />
        </Form.Item>
        <Form.Item label='数据库' field='database'>
          <Input placeholder='请输入数据库' />
        </Form.Item>
      </Form>
      </Drawer>
    </div>
  );
}

export default DataSource;
